/**
 *  @author 侯庆峰, 15/11/18.
 *
 *  @name LTOperationManager_hpp
 *
 *  @brief LTOpearationManager_hpp is used for opeartion managerment.
 *
 *  @copyright © 2015年 letv. All rights reserved.
 */

#ifndef LTOperationManager_h
#define LTOperationManager_h

#include "LTHttpOperation.h"
#include <semaphore.h>
#include <queue>
#include <mutex>
using namespace std;

class LTOperationManager{
public:
    /**
     *  单例
     */
    static LTOperationManager *GetInstance();
    
    /**
     * 创建http operation
     */
    LTHttpOperation *CreateOperation();
    
    /**
     * 异步执行http operation
     */
    void AddOperation(LTHttpOperation *operation);
    
    /**
     * 删除http operation
     */
    void DeleteOperation(LTHttpOperation *operation);
    
    /**
     * 同步执行http operation
     */
    bool ExcuteOperation(LTHttpOperation *operation);
    
    /**
     *  析构
     */
    virtual ~LTOperationManager();

protected:
    /**
     *  Get Pthread_id
     */
    pthread_t GetPid();
    
    /**
     *  设置curl共享数据
     */
    void SetShareCurlData();
    
    /**
     * 是否需要共享dns
     */
    bool IsShareDNS(char *url);
    
    
    /**
     *  设置共享参数的url
     */
    void SetShareURL(char* url);
    
    /**
     *  是否是共享的url连接
     */
    bool IsShareURL(char *url);
    
    /**
     * 删除http operation
     */
    void RemoveOperation(LTHttpOperation *operation);
    
private:
    pthread_t pid;//thread id
    CURLSH *shareCurlParam;//共享curl参数
    static CURLM *multiCurl; // 多curl句柄
    static LTOperationManager *operationManger; //单例对象
    
    std::mutex  _cond_mutex;
    std::mutex _queue_mutex;
    std::condition_variable _cond;
    
    map<CURL*, LTHttpOperation*> operationMap;
    vector<LTHttpOperation*> _addqueue;
    vector<LTHttpOperation*> _delqueue;
    
    vector<char*> shareURL;//共享参数的url
    
private:
    /**
     *  构造
     */
    LTOperationManager();
    
    /**
     *  创建线程
     */
    void CreateThread();
    
    /**
     *  启动监听
     */
    static void *CurlManger(void *pramater);
    
    /**
     *  监听连接
     */
    void Monitor(LTOperationManager *manger);
    
    /**
     *  完成连接处理
     */
    void CompletionConnection();
    /**
     *  Clean Memory function
     */
    static void CleanMemory(void *context);
    
private:
    LTHttpOperation *operation;
};

#endif /* LTOperationManager_h */